package com.jhmk.jhecis.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    /**
     * 没有实例化RestTemplate时，初始化RestTemplate
     * @return
     */
    @ConditionalOnMissingBean(RestTemplate.class)
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
        return restTemplate;
    }

    /**
     * 使用OkHttpClient作为底层客户端
     * @return
     */
    private ClientHttpRequestFactory getClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //客户端与服务端建立连接超时时间
        factory.setConnectTimeout(60000);
        //客户端从服务端读取数据的超时时间
        factory.setReadTimeout(60000);
        return factory;
    }



//    public void postForm() {
//        String url = "https://wwww.baidu.com";
//        OkHttpClient client = new OkHttpClient();
//        RequestBody body = new FormBody.Builder()
//                .add("username", "name")
//                .add("password", "666")
//                .build();
//        Request request = new Request.Builder().url(url).post(body).build();
//        Call call = client.newCall(request);
//        call.enqueue(callback);
//
//    }

//post json
//    public void postJson() {
//        String url = "https://wwww.baidu.com";
//        String json = "{\"username\":\"name\",\"password\":\"666\"}";
//        OkHttpClient client = new OkHttpClient();
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(json, mediaType);
//        Request request = new Request.Builder().url(url).post(body).build();
//        Call call = client.newCall(request);
//        call.enqueue(callback);
//    }
}